# -*- coding: utf-8 -*-
import os
import glob
import datetime


class LogManager:
    def __init__(self, base_dir="logs"):
        self.enabled = False  # 日志开关
        self.base_dir = base_dir
        self.current_log_file = None
        self.max_log_days = 7  # 保留最近7天的日志

        # 创建日志目录
        os.makedirs(base_dir, exist_ok=True)

    def get_log_file_path(self):
        """获取当前日期的日志文件路径"""
        current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        return os.path.join(self.base_dir, f"debug_{current_date}.log")

    def clean_old_logs(self):
        """清理旧的日志文件"""
        try:
            # 获取所有日志文件
            log_files = glob.glob(os.path.join(self.base_dir, "debug_*.log"))
            current_time = datetime.datetime.now()

            for log_file in log_files:
                # 从文件名获取日期
                file_date_str = os.path.basename(log_file).split('_')[1].split('.')[0]
                file_date = datetime.datetime.strptime(file_date_str, "%Y-%m-%d")

                # 如果文件超过指定天数，删除它
                if (current_time - file_date).days > self.max_log_days:
                    os.remove(log_file)
        except Exception as e:
            print(f"清理日志文件时出错: {str(e)}")

    def write_log(self, message, software_name=""):
        """写入日志"""
        if not self.enabled:
            return

        try:
            log_file = self.get_log_file_path()
            with open(log_file, "a", encoding='utf-8') as f:
                timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                software_prefix = f"[{software_name}] " if software_name else ""
                f.write(f"[{timestamp}] {software_prefix}{message}\n")
        except Exception as e:
            print(f"写入日志时出错: {str(e)}")